import _ from "lodash";
import VueResource from "vue-resource";
import { Message } from "element-ui";
// import {downloadjs} from "@yiducloud/yidu-util"
import router from "../router";
import { PREFIX } from "@/app-config";

const path = require("path");

const files = require.context("./", true, /.*(?<!index)\.js$/);
const service = _.reduce(
  files.keys(),
  (result, key) => {
    const name = path.basename(key, ".js");
    _.set(result, name, files(key).default || files(key));
    return result;
  },
  {}
);

function prepareService(Vue) {
  const { http } = Vue;

  const postDownload = (url, parameters) =>
    http
      .post(url, parameters, {
        responseType: "arraybuffer",
      })
      .then((resp) => {
        console.log(resp);
        const contentType = _.get(resp, "headers.map[content-type][0]");
        const content = new Blob([resp.data]);

        if (contentType.includes("application/json")) {
          const reader = new FileReader();
          reader.readAsText(content, "utf-8");
          reader.addEventListener("load", () => {
            try {
              const result = JSON.parse(reader.result);
              Message.error(
                _.get(result, "message") ||
                  _.get(result, "data", "下载出错请联系管理员")
              );
            } catch {
              Message.error("下载出错请联系管理员");
            }
          });
          return;
        }
        let name = decodeURIComponent(
          _.replace(
            _.get(resp, "headers.map[content-disposition][0]"),
            /.*filename=(.*)$/,
            "$1"
          )
        );
        name = _.trim(name, `"`);
        // downloadjs(content, name, contentType)
      });

  Object.defineProperties(http, {
    postDownload: {
      get() {
        return postDownload;
      },
    },
  });

  const services = {};
  Object.keys(service).forEach((k) => {
    services[k] = service[k](http);
  });
  return services;
}
// diamond目前字段不可配置，先mock下
function formatPermissionList(data) {
  const dataString = data
    ? JSON.stringify(data).replaceAll("frontUri", "url")
    : "[]";
  return JSON.parse(dataString);
}

export default {
  // eslint-disable-next-line sonarjs/cognitive-complexity
  install(Vue) {
    Vue.use(VueResource);
    Vue.$service = prepareService(Vue);
    Vue.prototype.$service = Vue.$service;

    // Vue.http.options.root = rootPath
    // 如果存在场地前缀 需要拦截并新增前缀
    if (PREFIX) {
      Vue.http.interceptors.push((request) => {
        if (request.url.indexOf("/api/") === 0) {
          request.url = `/${PREFIX}${request.url}`;
        }
      });
    }

    Vue.http.interceptors.push((request, next) => {
      let isPermissionCheck = false;
      if (request.url.includes("/api/rbac/opuser/getuseractionpermission")) {
        isPermissionCheck = true;
        request.params.appId = request.params.service_app_id;
      }
      next((response) => {
        const code = _.get(response, "body.code") || response.status;
        if (!_.isNil(code)) {
          switch (code) {
            case 401:
              if (Vue.$diamond) Vue.$diamond.auth.jumpToLogin("未登陆");
              Object.assign(response, {
                ok: false,
                _statusText: "未登陆",
                _status: 401,
              });
              break;
            case '1_040_001':
              Object.assign(response, {
                ok: false,
                _statusText: "没有相关权限",
                _status: '1_040_001',
              });
              break;
            case 1000:
              Object.assign(response, {
                ok: false,
                _statusText: "系统错误",
                _status: 1000,
              });
              break;
            case 1001:
              Object.assign(response, {
                ok: false,
                _statusText: "参数错误",
                _status: 1001,
              });
              break;
            case 1002:
              Object.assign(response, {
                ok: false,
                _statusText: "参数不能为空",
                _status: 1002,
              });
              break;
            case 1003:
              Object.assign(response, {
                ok: false,
                _statusText: "文件类型错误",
                _status: 1003,
              });
              break;
            case 1004:
              Object.assign(response, {
                ok: false,
                _statusText: "数据不存在",
                _status: 1004,
              });
              break;
            case 1005:
              Object.assign(response, {
                ok: false,
                _statusText: "操作失败",
                _status: 1005,
              });
              break;
            case 403:
              router.push("/auth");
              break;
            default: {
              /**/
            }
          }
        }
        if (isPermissionCheck) {
          response.data.data = formatPermissionList(response.data.data);
        }
        return response;
      });
    });
  },
};
